package com.lcy.struct.bTreePlus.disk.recovery.undo;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.lcy.struct.bTreePlus.disk.core.BPlusTreeFactory;
import com.lcy.struct.bTreePlus.disk.index.BTreeIndex;
import com.lcy.struct.bTreePlus.disk.log.LogUtils;
import com.lcy.struct.bTreePlus.disk.recovery.RecoveryCenter;
import lombok.SneakyThrows;

import java.util.ArrayList;
import java.util.List;

/**
 * @author lucongyang
 * @date Created in  10:20
 * @description 新增的逆向操作
 */
class UndoAdd {

    static UndoAdd getInstance() {
        return Singleton.INSTANCE;
    }

    /**
     * 生成undo日志
     *
     * @param bTreeIndex 主键
     */
    String getUndo(BTreeIndex bTreeIndex) {
        try {
            return "delete " + RecoveryCenter.getInstance().objectMapper.writeValueAsString(bTreeIndex);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("序列化失败");
        }
    }

    DoUndo.Suitable isSuit() {
        return (undoStr) -> undoStr.startsWith("delete ");
    }

    void doUndo(List<String> undoStrList) {
        List<Comparable[]> list = new ArrayList<>();
        for (String undoStr:undoStrList) {
            undoStr = undoStr.substring(7);
            BTreeIndex bTreeIndex = JSONObject.parseObject(undoStr, BTreeIndex.class);
            if (bTreeIndex.getIndexList().isEmpty()) {
                LogUtils.log("{},执行新增的逆向操作（删除）时失败，原因主键索引为空", undoStr);
                return;
            }
            Comparable[] c = new Comparable[bTreeIndex.getIndexList().size()];
            bTreeIndex.getIndexList().toArray(c);
            list.add(c);
        }
        BPlusTreeFactory.batchDel(list);
    }

    private static class Singleton {
        private static final UndoAdd INSTANCE = new UndoAdd();
    }

    private UndoAdd() {
    }
}
